"""
2024-07-30 戴尔服务器管理
"""
import requests
import json
import paramiko



BOARD_USER = 'root'
BOARD_PASSWORD = 'uuerp'
BOARD_ADDR = "https://192.168.0.50/"

# 设置SSH连接参数
hostname = '192.168.0.60'
port = 22  # SSH端口，默认是22
username = 'root'
password = 'asd1234567@'

def board_poweron() :
    """
    打开主板电源
    """
    url = BOARD_ADDR + 'redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset'
    payload = {'ResetType': 'On'}
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False, auth=(BOARD_USER,BOARD_PASSWORD))


def board_poweroff() :
    """
    关闭主板电源
    注意, 要先检查下虚拟机电源, 如果虚拟机电源还没关, 要先关虚拟机
    """
    url = BOARD_ADDR + 'redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset'
    payload = {'ResetType': 'ForceOff'}
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False, auth=(BOARD_USER,BOARD_PASSWORD))

def bord_powerstatus() :
    """
    获取主板电源状态
    """
    response = requests.get(BOARD_ADDR + 'redfish/v1/Systems/System.Embedded.1',verify=False,auth=(BOARD_USER,BOARD_PASSWORD))
    data = response.json()
    ## print data[u'PowerState']
    rs = data[u'PowerState']
    return rs


def vm_poweron(id) :
    """
    打开虚拟机电源
    """
    cmd = "vim-cmd vmsvc/power.on " + str(id)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # 连接SSH服务器
    client.connect(hostname, port, username, password)
    
    # 执行命令
    stdin, stdout, stderr = client.exec_command(cmd)
    
    # 获取命令输出
    datas = stdout.read().decode()
    print(datas)

    # 关闭连接
    client.close()

def vm_shutdown(id) :
    """
    关闭虚拟机电源
    """
    cmd = "esxcli vm process kill -t=soft -w=" + str(id)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # 连接SSH服务器
    client.connect(hostname, port, username, password)
    
    # 执行命令
    stdin, stdout, stderr = client.exec_command(cmd)
    
    # 获取命令输出
    datas = stdout.read().decode()
    print(datas)

    # 关闭连接
    client.close()


def vm_list_active() :
    """
    列出虚拟机列表及状态. 这里是只列出已开机的,FOR关机 
    """
    rs = []
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # 连接SSH服务器
    client.connect(hostname, port, username, password)
    
    # 执行命令
    stdin, stdout, stderr = client.exec_command('esxcli vm process list')
    
    # 获取命令输出
    datas = stdout.read().decode()
    ## print(datas)

    lines = datas.split('\n')
    cnt = len(lines)
    for i in range(0, cnt - 1) :
        data = lines[i]
        # if data.find('World ID') != -1 :
        #      print(data)
        if i < cnt - 2 and lines[i + 1].find('World ID') != -1 :
            servername = lines[i]
            wordid = lines[i + 1][13:]
            displayname = lines[i+5][16:]
            print(servername, wordid)
            rs.append((servername, wordid))
            i = i + 7
    # 关闭连接
    client.close()
    return rs


def vm_list_closed() :
    """
    列出已关闭的虚拟机, FOR开机
    """
    rs = []
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # 连接SSH服务器
    client.connect(hostname, port, username, password)
    
    # 执行命令
    stdin, stdout, stderr = client.exec_command('vim-cmd vmsvc/getallvms')
    
    # 获取命令输出
    datas = stdout.read().decode()
    print(datas)

    # lines = datas.split('\n')
    # cnt = len(lines)
    # for i in range(0, cnt - 1) :
    #     data = lines[i]
    #     # if data.find('World ID') != -1 :
    #     #      print(data)
    #     if i < cnt - 2 and lines[i + 1].find('World ID') != -1 :
    #         servername = lines[i]
    #         wordid = lines[i + 1][13:]
    #         displayname = lines[i+5][16:]
    #         print(servername, wordid)
    #         rs.append((servername, wordid))
    #         i = i + 7
    # 关闭连接
    client.close()
    return rs


def vm_find(name) :
    """
    根据虚拟机名称查找虚拟机
    """
    pass


def vm_poweron_all() :
    """
    打开所有虚拟机
    """
    pass


def vm_poweron_normal() :
    """
    打开工作中要打开的虚拟机
    """
    pass


if __name__ == '__main__' :
    ## print(bord_powerstatus())
    activevms = vm_list_active()
    print(activevms)
    ## vm_shutdown(2158407)
    vm_list_closed()
    ## vm_poweron(37)